'''
1找到输入框输入茶厂
2选择城市//a[@class="ui3-city-change-inner ui3-control-shadow"]
3点击搜索id="search-button"
4遍历城市
5取出名字，地址，电话
6每次点击给它sleep 2秒时间防止网络卡顿
'''
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from openpyxl import Workbook, load_workbook
import os
from time import sleep


# 搜索关键词
keywords = "茶厂"
# 城市数量
city_num = 0
# 保存路径
file_path = 'tea_factory.xlsx'
# 配置 Chrome 的选项，无界面模式（headless）以及中文语言
options = Options()
options.add_argument('--headless')
options.add_experimental_option('excludeSwitches', ['enable-automation'])
# options.add_experimental_option("debuggerAddress", "127.0.0.1:99999")  # 测试打开chrome界面
options.add_argument('lang=zh_CN.UTF-8')
# 启动 Chrome 浏览器
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.implicitly_wait(2)

# 点击搜索按钮


def searchbtn():
    search_button = driver.find_element(By.ID, 'search-button')
    driver.execute_script("$(arguments[0]).click()", search_button)
    sleep(2)

# 获取所有城市按钮并返回当前点击的位置


def CollectCities(index):
    city_change_btn = driver.find_element(
        By.XPATH, "//a[@map-on-click='selectCity']")
    driver.execute_script("$(arguments[0]).click()", city_change_btn)
    sleep(2)
    city_btns = driver.find_elements(
        By.XPATH, "//td[@class='sel-city-td-item']/a")
    sleep(0.5)
    if city_num == 0:
        city_num = len(city_btns)
    return city_btns[index]

# 显示选择城市并搜索


def SelectCity(pos):
    print(pos.text)
    driver.execute_script("$(arguments[0]).click()", pos)
    sleep(1)
    searchbtn()
    sleep(2)

# 查找下一页按钮并点击


def next_Page():
    GetCityInfo()
    page = 1
    while True:
        try:
            # driver.find_element没找到就会报错崩溃，不返回任何东西，所以用driver.find_elements检验
            next_none = driver.find_elements(
                By.XPATH, "//a[@class='next next-none']")
            if len(next_none) > 0:
                print("没有下一页了")
                return
            else:
                next_button = driver.find_element(
                    By.XPATH, "//a[@tid='toNextPage']")
                if next_button.is_enabled():
                    driver.execute_script(
                        "$(arguments[0]).click()", next_button)
                    sleep(2)
                    GetCityInfo()
                    page += 1
                    print("第{}页".format(page))
                    continue
        except:
            print("没有下一页按钮")
            return

# 获取一页的厂名地址电话


def GetCityInfo():
    try:
        city_info = driver.find_elements(
            By.XPATH, "//div[@class='ml_30 mr_90']")
        for city in city_info:
            data = city.text
            write_to_excel(file_path, data)
            sleep(0.5)
            print(data)
    except:
        print("这个市真菜，一个都没有")
        return


# 检查文件是否存在
def check_file_exists(file_path):
    return os.path.exists(file_path)

# 写入数据到Excel文件


def write_to_excel(file_path, data):
    if check_file_exists(file_path):
        # 表格文件已存在，打开并追加数据
        workbook = load_workbook(file_path)
        sheet = workbook.active
    else:
        # 表格文件不存在，创建新表格并添加数据
        workbook = Workbook()
        sheet = workbook.active
        # 添加表头
        sheet.append(['名称', '地址', '电话'])

    try:
        info = data.split("\n")
        sheet.append(info)
        # 保存文件
        workbook.save(file_path)
        print("数据保存成功！")
    except NoSuchElementException:
        print("没有数据")
    return 0

# 关闭注册界面，测试的时候打开chrome界面才用得到，真正爬取不需要打开chrome界面就用不到


def colse_regester():
    while True:
        sleep(1)
        is_find_regester = driver.find_elements(
            By.XPATH, "//a[@id='TANGRAM__PSP_37__closeBtn']")
        if len(is_find_regester) > 0:
            driver.execute_script(
                "$(arguments[0]).click()", is_find_regester[0])
            return


def TestMapGet():
    # 发起百度地图的请求
    driver.get('https://map.baidu.com')
    sleep(2)

    # colse_regester()
    # 查找“茶厂”这个关键词的输入框，并输入关键词
    search_box = driver.find_element(By.ID, 'sole-input')
    wait1 = WebDriverWait(driver, timeout=2)
    search_box.send_keys(keywords)

    # 筛选城市
    for index in range(0, city_num):
        pos = CollectCities(index)
        SelectCity(pos)
        next_Page()

    # 关闭 Chrome 浏览器驱动
    driver.quit()
    print('信息已成功提取并保存到', 'tea_factory.xlsx', '中')


if __name__ == "__main__":
    TestMapGet()
